/*
* Created on Tue Jun 13 2023 by Admin
*
* Copyright (c) 2023 shuangdi
*
* description: knowledge
*
* date: 2025/3/13
*/
<template>
  <div class="root_app">
    <iframe src="http://172.16.20.72:2000/szxbgraph" width="100%" height="100%" id="iframeDom"/>
  </div>
</template>

<script setup>
import {onMounted} from "vue";
import {getCourseGraphData} from "@/api/index.js";

onMounted(() => {
  // 接收消息
  receiveMessage()
})

// 发送消息
function postMessage() {
  // 图谱配置项和参数
  let configurationGraph = {
    optionsConfig: {
      isNewData: true,
      bindNodeClick: true,
      layout: "d3Force",
      // layout: "compactBox",
      padding: [80, 80, 80, 80],
      animation: true,
      defaultNodeSize: 40,
      defaultLabelSize: 12,
      defaultAutoFit: 'center',
    },
    configuration: {
      nodeId: "id",
      nodeLabel: "label",
      nodeType: 'type',
      edgeLabel: "label",
      source: "source",
      target: "target",
    },
    courseName: "高中地理",
    data: []
  }
  // 知识点提取出来
  let knowledgeData = {
    nodes: [],
    edges: []
  }
  // 获取课程的图谱数据
  // 1911603842693210113	高中地理
  // 1922502117046788097	思政
  // 1924751678557442049	同济医学院知识库

  // http://119.45.164.254/sundeinfo/
  // tjyxyAdmin/123456(同济医学院管理员)
  // "kb_id": "1922502117046788097
  getCourseGraphData({kb_id: "1911603842693210113"}).then((res) => {
    res.edges.forEach((item, index) => {
      if (item.label === '相关') {
        item.label = '有关'
      }
    })
    // 提取知识点数据
    knowledgeData.nodes = res.nodes.filter(v => v.label === 'Resource')
    knowledgeData.edges = res.edges.filter(v => v.label === '相关')
    // 提取图谱数据
    const nodes = res.nodes.filter(v => v.label !== 'Resource')
    const edges = res.edges.filter(v => v.label !== '相关')
    const graphData = {nodes, edges}
    // 把提取到的知识点添加到图谱数据中，形成树形结构
    configurationGraph.data = findKnowledgeParent(knowledgeData, graphData)
    // 打印需要发送子组件的图谱数据
    let postData = {
      signal: 'graphData',
      data: configurationGraph
    }
    const iframeDom = document.getElementById('iframeDom')
    iframeDom?.contentWindow.postMessage(postData, '*')
  })


// 查找知识点的父级
  function findKnowledgeParent(resource, graphData) {
    if (resource.nodes.length) {
      resource.edges.forEach(v1 => {
        graphData.nodes.forEach(v2 => {
          if (v1.source === v2.id) {
            let node = resource.nodes.find(v => v.id === v1.target)
            let data = v2.children ? v2.children : [v2]
            v2.children = [node, ...data]
          }
        })
      })
    }
    return graphData
  }
}

// 接收消息
function receiveMessage() {
  // 处理接收到的消息
  window.addEventListener('message', function (event) {
    if (event.data.signal && event.data.signal === "iframeFinish") {
      postMessage()
    }
  });
}
</script>
<style scoped>
.root_app {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background: gray;
}
</style>
